Binary search is an efficient search algorithm used to find a specific element in a sorted array. The algorithm repeatedly divides the array in half and checks if the middle element matches the target. If not, it narrows down the search to the left or right half of the array, and the process continues until the target element is found or the search space becomes empty.
#include <stdio.h>
// Binary Search function
int binarySearch(int arr[], int n, int target) {
int left = 0;
int right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid; // Found the target at index mid
} else if (arr[mid] < target) {
left = mid + 1; // Target lies in the right half
} else {
right = mid - 1; // Target lies in the left half
}
}
return -1; // Target not found
}
int main() {
int sortedArray[] = {10, 20, 30, 40, 50, 60, 70};
int n = sizeof(sortedArray) / sizeof(sortedArray[0]);
int target = 40;
int index = binarySearch(sortedArray, n, target);
if (index != -1) {
printf("Element %d found at index %d.\n", target, index);
} else {
printf("Element not found in the array.\n");
}
return 0;
}
Element 40 found at index 3.
What is binary search in C?
What is the time complexity of binary search?
What is the key requirement for binary search to work?
What does binary search do to the search space in each step?
In binary search, what is checked to decide whether to search the left or right half of the array?